//材质属性side：
//THREE.FrontSide  前面渲染，默认
// THREE.BackSide 背面渲染
// THREE.DoubleSide 双面渲染

import { useEffect } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

function SimpleCubeWithLight() {
  useEffect(() => {
    // 1. 初始化场景、相机、渲染器
    const scene = new THREE.Scene();
    scene.background = new THREE.Color('white');

    const fov = 75;
    const aspect = 2; // the canvas default
    const near = 0.1;
    const far = 25;
    const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
    camera.position.z = 5;
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    // 轨道控制器
    const controls = new OrbitControls(camera, renderer.domElement);

    // // 2. 创建立方体
    // function makeInstance(geometry, color, x, y, z) {
    //   const material = new THREE.MeshPhongMaterial({
    //     color,
    //     transparent: true,
    //     opacity: 0.5,
    //     side: THREE.DoubleSide,// 实现双面渲染
    //   });

    //   const cube = new THREE.Mesh(geometry, material);
    //   scene.add(cube);
    //   cube.position.set(x, y, z);

    //   return cube;
    // }
    // 直接使用side: THREE.DoubleSide实现双面渲染时，会导致左面透明度消失，使用下面方法
    function makeInstance(geometry, color, x, y, z) {
      [THREE.BackSide, THREE.FrontSide].forEach((side) => {
        const material = new THREE.MeshPhongMaterial({
          color,
          opacity: 0.5,
          transparent: true,
          side,
        });

        const cube = new THREE.Mesh(geometry, material);
        scene.add(cube);

        cube.position.set(x, y, z);
      });
    }
    function hsl(h, s, l) {
      return new THREE.Color().setHSL(h, s, l);
    }

    {
      const d = 0.8;
      const geometry = new THREE.BoxGeometry(1, 1, 1);
      makeInstance(geometry, hsl(0 / 8, 1, 0.5), -d, -d, -d);
      makeInstance(geometry, hsl(1 / 8, 1, 0.5), d, -d, -d);
      makeInstance(geometry, hsl(2 / 8, 1, 0.5), -d, d, -d);
      makeInstance(geometry, hsl(3 / 8, 1, 0.5), d, d, -d);
      makeInstance(geometry, hsl(4 / 8, 1, 0.5), -d, -d, d);
      makeInstance(geometry, hsl(5 / 8, 1, 0.5), d, -d, d);
      makeInstance(geometry, hsl(6 / 8, 1, 0.5), -d, d, d);
      makeInstance(geometry, hsl(7 / 8, 1, 0.5), d, d, d);
    }
    // 光源
    function addLight(...pos) {
      const color = 0xffffff;
      const intensity = 1;
      const light = new THREE.DirectionalLight(color, intensity);
      light.position.set(...pos);
      scene.add(light);
    }
    addLight(-1, 2, 4);
    addLight(1, -1, -2);

    // 5. 渲染循环
    function animate() {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    }
    animate();

    // 清理函数
    return () => {
      document.body.removeChild(renderer.domElement);
    };
  }, []);

  return <div />;
}

export default SimpleCubeWithLight;
